/*
License:
	MIT-style license

Author:
	Jan Kassens
*/
var MooRemote = new Class({

	initialize: function(functions, options){
		this.$options = $merge({
			'url': undefined
		}, options);
		functions.each(function(fn){
			this[fn] = function(){
				return new MooRequest(this.$options.url, fn, arguments);
			};
		}, this);
	}

});

var MooRequest = XHR.extend({

	initialize: function(url, fn, args){
		this.parent();
		this.setHeader('X-Requested-With', 'MooRequest');
		this.send(url || window.location.href, "call=" + encodeURIComponent(Json.toString([fn, args])));
	},

	onSuccess: function(){
		var response = Json.evaluate(this.transport.responseText);
		if(response.script) window.execScript ? window.execScript(response.script) : window.setTimeout(response.script, 0);
		if(response.error) this.fireEvent('onError', response.error);
		else this.fireEvent('onSuccess', response.args ? [response.args] : []);
	},

	callback: function(fn){
		return this.addEvent('onSuccess', fn);
	}

});